package main

import (
	"errors"
	"fmt"
	"net"
)

func GetLocalIPv4() (ip string, err error) {
	addrList, err := net.InterfaceAddrs()
	if err != nil {
		return ip, err
	}
	for _, addr := range addrList {
		// 过滤掉回环地址
		if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			ipv4 := ipNet.IP.To4()
			// 如果ip不符合ipv4格式，继续查找下一个
			if ipv4 == nil {
				continue
			}
			return ipv4.String(), nil
		}
	}
	return ip, errors.New("no find ip address")
}

func main() {
	// 获取本地ip v4地址
	ip, err := GetLocalIPv4()
	if err != nil {
		ip = "192.168.1.1" // 默认地址
	}

	fmt.Printf("ip = %sn", ip)
	// 输出：ip = 192.168.2.21
}
